<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Local variable</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Local_variable"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Local_variable rootpage-Local_variable skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Local variable</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<p>In <a href="Computer_science" title="Computer science">computer science</a>, a <b>local variable</b> is a <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">variable</a> that is given <i>local <a href="Scope_(programming)" class="mw-redirect" title="Scope (programming)">scope</a></i>. A local variable reference in the <a href="Subroutine" class="mw-redirect" title="Subroutine">function</a> or <a href="Block_(programming)" title="Block (programming)">block</a> in which it is declared overrides the same variable name in the larger scope. In <a href="Programming_language" title="Programming language">programming languages</a> with only two levels of visibility, local variables are contrasted with <a href="Global_variables" class="mw-redirect" title="Global variables">global variables</a>. On the other hand, many <a href="ALGOL" title="ALGOL">ALGOL</a>-derived languages allow any number of nested levels of visibility, with private variables, functions, constants and types hidden within them, either by nested blocks or <a href="Nested_function" title="Nested function">nested functions</a>. Local variables are fundamental to <a href="Procedural_programming" title="Procedural programming">procedural programming</a>, and more generally <a href="Modular_programming" title="Modular programming">modular programming</a>: variables of local scope are used to avoid issues with <a href="Side-effect_(computer_science)" class="mw-redirect" title="Side-effect (computer science)">side-effects</a> that can occur with <a href="Global_variable" title="Global variable">global variables</a>.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Scope">Scope</h2></div>
<p>Local variables may have a lexical or dynamic <a href="Scope_(programming)" class="mw-redirect" title="Scope (programming)">scope</a>, though lexical (static) scoping is far more common. In lexical scoping (or lexical scope; also called static scoping or static scope), if a variable name's scope is a certain block, then its scope is the program text of the block definition: within that block's text, the variable name exists, and is bound to the variable's value, but outside that block's text, the variable name does not exist. By contrast, in dynamic scoping (or dynamic scope), if a variable name's scope is a certain block, then its scope is that block and all functions transitively called by that block (except when overridden again by another declaration); after the block ends, the variable name does not exist. Some languages, like <a href="Perl" title="Perl">Perl</a> and <a href="Common_Lisp" title="Common Lisp">Common Lisp</a>, allow the programmer to choose static or dynamic scoping when defining or redefining a variable. Examples of languages that use dynamic scoping include <a href="Logo_(programming_language)" title="Logo (programming language)">Logo</a>, <a href="Emacs_lisp" class="mw-redirect" title="Emacs lisp">Emacs lisp</a>, and the shell languages <a href="Bash_(Unix_shell)" title="Bash (Unix shell)">bash</a>, <a href="Dash_(shell)" class="mw-redirect" title="Dash (shell)">dash</a>, and the MirBSD Korn shell (<a href="Mksh" class="mw-redirect" title="Mksh">mksh</a>)'s "local" declaration. Most other languages provide lexically scoped local variables.
</p><p>In most languages, local variables are <a href="Automatic_variable" title="Automatic variable">automatic variables</a> stored on the <a href="Call_stack" title="Call stack">call stack</a> directly. This means that when a <a href="Recursion_(computer_science)" title="Recursion (computer science)">recursive function</a> calls itself, local variables in each instance of the function are given distinct <a href="Memory_address" title="Memory address">addresses</a>. Hence variables of this scope can be declared, written to, and read, without any risk of <a href="Side-effect_(computer_science)" class="mw-redirect" title="Side-effect (computer science)">side-effects</a> to functions outside of the block in which they are declared.
</p><p>Programming languages that employ <i><a href="Call_by_value" class="mw-redirect" title="Call by value">call by value</a></i> semantics provide a called subroutine with its own local copy of the <a href="Function_argument" class="mw-redirect" title="Function argument">arguments</a> passed to it. In most languages, these local parameters are treated the same as other local variables within the subroutine. In contrast, <i><a href="Call_by_reference" class="mw-redirect" title="Call by reference">call by reference</a></i> and <i><a href="Call_by_name" class="mw-redirect" title="Call by name">call by name</a></i> semantics allow the parameters to act as aliases of the values passed as arguments, allowing the subroutine to modify variables outside its own scope.
</p>
<div class="mw-heading mw-heading2"><h2 id="Static_local_variables">Static local variables</h2></div>
<p>A special type of local variable, called a <i>static local,</i> is available in many mainstream languages (including <a href="C_(programming_language)" title="C (programming language)">C</a>/<a href="C%2B%2B" title="C++">C++</a>, <a href="Visual_Basic" title="Visual Basic">Visual Basic</a>, <a href="Visual_Basic_(.NET)" title="Visual Basic (.NET)">VB.NET</a> and <a href="PHP" title="PHP">PHP</a>) which allows a value to be retained from one call of the function to another – it is a <a href="Static_variable" title="Static variable">static variable</a> with local scope. In this case, recursive calls to the function also have access to the (single, <a href="Static_memory_allocation" class="mw-redirect" title="Static memory allocation">statically allocated</a>) variable. In all of the above languages, static variables are declared as such with a special <i>storage class</i> keyword (e.g., <code>static</code>).
</p><p>Static locals in global functions have the same lifetime as <a href="Static_global_variable" class="mw-redirect" title="Static global variable">static global variables</a>, because their value remains in memory for the life of the program,<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> but have <a href="Function_scope" class="mw-redirect" title="Function scope">function scope</a> (not global scope), as with automatic local variables.
</p><p>This is distinct from other usages of the <a href="Static_(keyword)" title="Static (keyword)"><code>static</code> keyword</a>, which has several different meanings in various languages.
</p>
<div class="mw-heading mw-heading2"><h2 id="Local_variables_in_Perl">Local variables in Perl</h2></div>
<p><a href="Perl" title="Perl">Perl</a> supports both dynamic and lexically-scoped local variables. The keyword <code>local</code> is used to define local dynamically-scoped variables, while <code>my</code> is used for local lexically-scoped variables. Since dynamic scoping is less common today, the Perl documentation warns that "<code>local</code> isn't what most people think of as “local”.".<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup> Instead, the <code>local</code> keyword gives a temporary, <a href="Scope_(computer_science)" title="Scope (computer science)">dynamically-scoped</a> value to a global (package) variable, which lasts until the end of the enclosing block. However, the variable is visible to any function called from within the block.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup> To create lexically-scoped local variables, use the <code>my</code> operator instead.<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p><p>To understand how it works consider the following code:
</p>
<div class="mw-highlight mw-highlight-lang-perl mw-content-ltr" dir="ltr"><pre><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span>
<span class="k">sub</span><span class="w"> </span><span class="nf">f</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nb">local</span><span class="w"> </span><span class="nv">$a</span><span class="p">;</span>
<span class="w"> </span><span class="nv">$a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span>
<span class="w"> </span><span class="n">g</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">sub</span><span class="w"> </span><span class="nf">g</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">print</span><span class="w"> </span><span class="s">"$a\n"</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">g</span><span class="p">();</span>
<span class="n">f</span><span class="p">();</span>
<span class="n">g</span><span class="p">();</span>
</pre></div>
<p>this will output:
</p>
<pre>1
2
1
</pre>
<p>This happens since the global variable $a is modified to a new <i>temporary</i> (local) meaning inside <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">f()</code>, but the global value is restored upon leaving the scope of <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">f()</code>.
</p><p>Using <code>my</code> in this case instead of <code>local</code> would have printed 1 three times since in that case the <code>$a</code> variable would be limited to the static scope of the function <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">f()</code> and not seen by <code class="mw-highlight mw-highlight-lang-text mw-content-ltr" style="" dir="ltr">g()</code>.<br> Randal L. Schwartz and Tom Phoenix argue that the operator <code>local</code> should have had a different name like <code>save</code>.<sup id="cite_ref-5" class="reference"><a href="#cite_note-5"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Local_variables_in_Ruby">Local variables in Ruby</h2></div>
<p><a href="Ruby_(programming_language)" title="Ruby (programming language)">Ruby</a> as a language was inspired also by Perl, but in this case, the notation was made simpler: a global variable name must be preceded by a $ sign, like <code>$variable_name</code>, while a local variable has simply no $ sign in front of its name, like <code>variable_name</code> (while in perl all scalar values have a $ in front). Note that Ruby only provides built-in support for statically-scoped local variables like Perl's <code>my</code>, not dynamically-scoped local variables like Perl's <code>local</code>. There is at least one library for Ruby that provides dynamically-scoped variables.
<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<ul><li><a href="Global_variable" title="Global variable">Global variable</a></li>
<li><a href="Non-local_variable" title="Non-local variable">Non-local variable</a></li></ul>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */
.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}
/* end https://en.wikipedia.org/ */
</style><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf">"Current C standard"</a> <span class="cs1-format">(PDF)</span>.</cite> <span style="font-size: 85%;">(3.61 MB)</span> (as of 2009). In particular, see section 6.2.4 “Storage durations of objects”, page 32.</span>
</li>
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://perldoc.perl.org/functions/local.html">perldoc.perl.org: local</a></span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()">perldoc.perl.org: perlsub: Temporary Values via <code>local()</code></a></span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()">perldoc.perl.org: perlsub: Private Variables via <code>my()</code></a></span>
</li>
<li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text"><cite id="CITEREFRandal_L._Schwartz_and_Tom_Phoenix2001" class="citation book cs1">Randal L. Schwartz and Tom Phoenix (2001-07-01). <a rel="nofollow" class="external text" href="https://archive.org/details/learningperl00schw"><i>Learning Perl 3rd edition</i></a>. O'REILLY. paragraph 4.7. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-596-00132-0</bdi>.</cite></span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text">
Conrad Irwin.
"LSpace: Dynamic scope for Ruby".
December 2012
<a rel="nofollow" class="external free" href="http://cirw.in/blog/lspace">http://cirw.in/blog/lspace</a>
Retrieved 2013-10-16.</span>
</li>
</ol></div></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2023-11-25" href="https://en.wikipedia.org/wiki/?title=Local_variable&oldid=1186802448">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>
</body></html>